<template>
  <div class="contentWrapper">
    <div class="contentTitle">
      <div class="title">简历优化</div>
      <!-- <div class="topFileName" v-if="fileUrl">
        <div class="fileTitle">当前预览文件的文件名：</div>
        <div class="fileName">{{ currentFileName }}</div>
        <span class="file-delete" @click="deleteFile(currentFileId)">
          <i class="el-icon-delete"></i>
        </span>
      </div> -->
    </div>
    <div class="contentContainer">
      <div class="contentTop">
        <div class="reuploadBtn" v-if="fileUrl">
          <el-button
            type="primary"
            round
            plain
            size="mini"
            style="display: flex"
            icon="el-icon-upload"
            @click="updateFile"
          >
            更新当前文件</el-button
          >
        </div>

        <div class="downloadBtn" v-if="fileUrl">
          <el-button
            round
            plain
            size="mini"
            style="display: flex"
            icon="el-icon-download"
            @click="handleDownloadClick"
          >
            下载</el-button
          >
        </div>
        <div class="downloadBtn" v-if="fileUrl">
          <el-button
            round
            plain
            size="mini"
            style="display: flex"
            icon="el-icon-plus"
            @click="uploadFile"
          >
            新增文件</el-button
          >
        </div>
        <el-upload
          @click.stop
          v-show="false"
          class="upload-file"
          :multiple="false"
          id="uploadFile"
          :action="uploadAction"
          :accept="accept"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
        >
        </el-upload>
        <el-dialog
          title="上传文件"
          title-class="custom-dialog-title"
          :visible.sync="dialogVisible"
          width="500px"
          :before-close="handleClose"
          append-to-body
        >
          <div class="dialog-tips">
            提示:请上传正确的文本格式文件，如pdf、docx
          </div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="上传者：">
              <el-select
                style="width: 100%"
                v-model="form.consultantId"
                filterable
                :disabled="!isManager"
                placeholder="请选择上传者"
              >
                <el-option
                  v-for="item in consultantList"
                  :key="item.consultantId"
                  :label="item.consultantName"
                  :value="item.consultantId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSelectFile"
              >选择文件</el-button
            >
          </span>
        </el-dialog>
      </div>
      <div class="contentMain" v-loading="pdfLoading">
        <template v-if="fileUrlType !== 'empty'">
          <div :class="['officeWrapper']" style="width: 850px">
            <el-scrollbar class="scroll">
              <vue-office-pdf
                :src="fileUrl"
                @rendered="renderedHandler"
                @error="errorHandler"
                v-if="fileUrlType === 'pdf'"
              />
              <vue-office-docx
                :src="fileUrl"
                @rendered="renderedHandler"
                @error="errorHandler"
                v-if="fileUrlType === 'word'"
              />
            </el-scrollbar>
          </div>
          <div class="fileOverview" v-if="fileList.length">
            <div class="overViewTitle">文件预览</div>
            <ul style="height: 100%; overflow-y: auto">
              <li
                v-for="(item, index) in fileList"
                :key="index"
                @click="changeFileUrl(item, index)"
                :class="[activeLiIndex === index ? 'activeLi' : 'fileLi']"
              >
                <div class="file-name">
                  {{ index + 1 }}. {{ item.fileName }}
                </div>
                <div class="consultant-time">
                  {{ item.updateTime }}
                </div>
                <div class="consultant-name">
                  <div class="consultant-name-left">
                    {{ item.consultantName }}上传
                  </div>
                  <span
                    class="consultant-name-right"
                    @click.stop="deleteFile(item.id)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </div>
              </li>
            </ul>
          </div>
        </template>
        <div v-else class="empty">
          <Empty />
          <el-button
            v-if="!fileUrl"
            type="primary"
            round
            plain
            size="small"
            style="display: flex; margin-top: 12px"
            icon="el-icon-upload"
            @click="uploadFile"
          >
            上传文件</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import VueOfficePdf from '@vue-office/pdf';
import VueOfficeDocx from '@vue-office/docx';
import { download } from '@/utils/fileSaver';
import { judgeFileType } from '@/utils/judgeFileType';
import {
  getFileList,
  getHandleFileAuth,
  uploadCareerFile,
  updateCareerFile,
  deleteFile,
  getConsultantNameList
} from '@/api/index';
export default {
  name: 'Disc',
  components: {
    VueOfficePdf,
    VueOfficeDocx
  },
  props: {
    selectedRow: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      drawerVisible: false,
      fileName: '',
      activeLiIndex: 0, // 当前激活的li
      fileUrl: '',
      fileUrlType: 'empty',
      uploadAction: 'https://upload.yl1001.com/upload/files/save',
      accept: '.pdf,.PDF,.docx',
      fileGetting: false,
      loading: false,
      showEmpty: false,
      pdfDoc: null,
      pageNum: 1,
      src: '',
      userId: '',
      pageRendering: false,
      pageNumPending: null,
      pdfLoading: false,
      fileList: [], // 顾问总结的报告 注意只是顾问总结的报告
      currentFileId: '',
      currentFileName: '',
      isUpdateFile: false, //true 更新文件 false 上传文件
      consultantList: [], //可选择的上传者名字
      dialogVisible: false, //弹窗确认上传者
      isManager: false, // 是否是管理员
      form: {
        consultantId: ''
      }
    };
  },
  mounted() {
    this.getFileList(true);
    this.getConsultantNameListFn();
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
    },
    handleSelectFile() {
      if (!this.form.consultantId) {
        this.$message.error('请选择上传者！');
        return;
      }

      this.dialogVisible = false;
      this.uploadMedia();
    },
    async getConsultantNameListFn() {
      const params = {
        pageNo: 1,
        pageSize: 1000
      };
      const res = await getConsultantNameList(params);
      if (res.code == 200) {
        console.log('res', res);
        this.consultantList = res.data;
      }
    },
    async updateFile() {
      this.isUpdateFile = true;
      this.uploadMedia();
    },
    async uploadFile() {
      this.isUpdateFile = false;
      const res = await getHandleFileAuth();
      if (res.code != 200) {
        this.$message.error(res.status_desc);
        return;
      }
      console.log('----getHandleFileAuth----->', res);
      this.isManager = res.data.isManager;
      if (this.isManager != 1) {
        this.consultantList = [
          {
            consultantName: res.data.consultantName,
            consultantId: res.data.consultantId
          }
        ]; //列表只有当前登录人
        this.form.consultantId = res.data.consultantId; //this.selectedRow.consultantId
        console.log(
          '----------getHandleFileAuth----------->',
          this.consultantList
        );
      }
      this.dialogVisible = true;
    },
    async updateCareerFile(fileUrl) {
      const params = {
        id: this.currentFileId,
        fileUrl: fileUrl,
        fileName: this.fileName
      };
      updateCareerFile(params).then((res) => {
        if (res.code == 200) {
          this.fileUrl = fileUrl;
          this.fileUrlType = judgeFileType(this.fileUrl);
          this.$message({
            type: 'success',
            message: '更新成功'
          });
          this.getFileList(false);
        } else {
          this.$message.error(res.status_desc);
        }
      });
    },
    async deleteFile(currentFileId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            id: currentFileId
          };
          deleteFile(params).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功'
              });
              this.fileList = [];
              (this.fileUrl = ''), (this.fileUrlType = 'empty');
              this.currentFileId = '';
              this.currentFileName = '';
              this.activeLiIndex = 0;
              this.getFileList(true);
            } else {
              this.$message.error(res.status_desc);
            }
          });
        })
        .catch(() => {});
    },
    changeFileUrl(item, index) {
      if (this.activeLiIndex == index) return;
      this.pdfLoading = true;
      this.fileUrl = item.fileUrl;
      this.fileUrlType = judgeFileType(this.fileUrl);
      this.currentFileId = item.id;
      this.currentFileName = item.fileName;
      this.activeLiIndex = index;
      this.drawerVisible = false;
    },
    showFileList() {
      this.drawerVisible = true;
    },
    async uploadCareerFile(fileUrl) {
      const params = {
        personId: this.selectedRow.personId,
        consultantId: this.form.consultantId, //this.selectedRow.consultantId
        fileType: '4',
        fileUrl: fileUrl,
        fileName: this.fileName
      };
      console.log(
        '-uploadCareerFile------->------->',
        this.form.consultantId,
        this.selectedRow.consultantId
      );
      const res = await uploadCareerFile(params);
      if (res.code == 200) {
        this.fileUrl = fileUrl;
        this.fileUrlType = judgeFileType(this.fileUrl);
        this.$message({
          type: 'success',
          message: '上传成功'
        });
        this.getFileList(true);
      } else {
        this.$message.error(res.status_desc);
      }
    },
    async getFileList(showFirstFile) {
      this.pdfLoading = true;
      const params = {
        personId: this.selectedRow.personId,
        // consultantId: this.selectedRow.consultantId,
        fileType: '4'
      };
      const res = await getFileList(params);
      this.pdfLoading = false;
      if (res.code == 200 && Array.isArray(res.data) && res.data.length) {
        this.fileList = res.data;
        this.fileUrl = res.data[showFirstFile ? 0 : this.activeLiIndex].fileUrl;
        this.fileUrlType = judgeFileType(this.fileUrl);
        this.currentFileId =
          res.data[showFirstFile ? 0 : this.activeLiIndex].id;
        this.currentFileName =
          res.data[showFirstFile ? 0 : this.activeLiIndex].fileName;
        this.activeLiIndex = showFirstFile ? 0 : this.activeLiIndex;
      }
      console.log(this.fileUrlType);
      console.log(this.fileUrl);
    },
    uploadMedia() {
      if (!this.selectedRow.consultantId) {
        this.$message.error('该用户还没绑定顾问！');
        return;
      }
      // 防抖
      if (this.fileGetting) {
        return;
      }
      this.fileGetting = true;
      setTimeout(() => {
        this.fileGetting = false;
      }, 1000);
      setTimeout(() => {
        document.querySelector('#uploadFile').querySelector('input').click();
      }, 100);
    },
    beforeUpload(files) {
      this.fileName = files.name;
      if (
        [
          'application/pdf',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-powerpoint'
        ].indexOf(files.type) == -1
      ) {
        this.$message.error('请上传正确的文本格式文件，如pdf doc docx');
        return false;
      }
    },
    handleUploadSuccess(data) {
      // this.fileUrl = data.data[0];
      // this.fileUrlType = judgeFileType(this.fileUrl);
      if (this.isUpdateFile) {
        this.updateCareerFile(data.data[0]);
      } else {
        this.uploadCareerFile(data.data[0]);
      }
    },
    handleDownloadClick() {
      download(this.fileUrl, this.currentFileName);
    },
    renderedHandler() {
      this.pdfLoading = false;
    },
    errorHandler() {
      this.$message.info('pdf正在渲染中...');
      this.pdfLoading = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.contentWrapper {
  height: 100%;
  .contentTitle {
    margin-bottom: 17px;
    display: block;
    align-items: center;
    .title {
      font-size: 22px;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: 800;
      color: #222222;
      line-height: 30px;
      margin-bottom: 10px;
    }
    .topFileName {
      display: flex;
      font-size: 16px;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: 400;
      color: #555;
      line-height: 30px;
      // margin-bottom: 20px;
      .fileName {
        max-width: 500px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        font-weight: 600;
        color: #7052ff;
      }
      .file-delete {
        margin: 0px 24px;
      }
    }
  }
  .contentContainer {
    height: calc(100% - 62px);
    .contentTop {
      display: flex;
      align-items: center;
      margin-bottom: 14px;
      position: relative;
      .downloadBtn {
        margin-left: 14px;
        /deep/.el-button.is-round {
          background-color: transparent;
        }
        .svg-icon {
          font-size: 16px;
          margin-right: 5px;
        }
      }
      img {
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
    }
    .contentMain {
      display: flex;
      width: 100%;
      height: calc(100% - 40px);
      .officeWrapper {
        border-radius: 8px 0px 8px 8px;
        border: 1px solid #e6e5e7;
        overflow: hidden;
        height: 100%;
        .scroll {
          height: 100%;
        }
      }
      .empty {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
      /deep/.vue-office-pdf-wrapper {
        background-color: #ffffff !important;
        width: 100%;
        overflow: hidden;
      }
      /deep/ .docx-wrapper {
        background-color: #ffffff !important;
        width: 100%;
        overflow: hidden;
      }
      /deep/.vue-office-pdf {
        overflow-x: hidden;
      }
      /deep/ .vue-office-docx {
        overflow-x: hidden;
      }
    }
  }
  .fileOverview {
    position: relative;
    width: 222px;
    .overViewTitle {
      width: 109px;
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #222222;
      line-height: 22px;
      position: absolute;
      margin-top: -30px;
    }
  }
  .fileLi,
  .activeLi {
    cursor: pointer;
    font-size: 16px;
    font-family: PingFang-SC, PingFang-SC;
    line-height: 20px;
    padding: 12px 0px;
    .file-name {
      margin: auto 12px;
      font-size: 14px;
    }
    .consultant-time {
      margin: auto 12px;
      font-size: 12px;
      line-height: 30px;
    }
    .consultant-name {
      display: flex;
      margin: auto 12px;
      font-size: 12px;
      justify-content: space-between;
      .consultant-name-left {
        width: 80%;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .consultant-name-right {
        width: 20px;
        height: 20px;
      }
    }
  }
  .fileLi {
    .file-name {
      color: #888888;
    }
    .consultant-time {
      color: #bfbfbf;
    }
    .consultant-name {
      .consultant-name-left {
        color: #bfbfbf;
      }
    }
  }
  .activeLi {
    background: #f2e9ff;
    .file-name {
      color: #7052ff;
    }
    .consultant-time {
      color: #a099c4;
    }
    .consultant-name {
      .consultant-name-left {
        color: #a099c4;
      }
    }
  }
}
::v-deep .el-button.is-round {
  span {
    display: flex;
    align-items: center;
  }
}
.dialog-tips {
  margin-bottom: 20px;
  font-size: 14px;
  color: #999;
}
::v-deep .el-form-item__label {
  text-align: left;
}
::v-deep .el-dialog__title {
  font-size: 16px !important;
  color: #333;
}
::v-deep .el-dialog__body {
  padding: 10px 20px !important;
  border-bottom: 1px solid #f2f2f2;
}
</style>
